<template>
  <div class="announcement-component">
    <button class="announcement-btn" @click="toggleAnnouncementList">
      <span class="announcement-icon">📢</span>
      <span class="announcement-text">系统公告</span>
      <span v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</span>
    </button>
    
    <div v-if="showAnnouncementList" class="announcement-dropdown">
      <div class="announcement-header">
        <h3>系统公告</h3>
        <button class="close-btn" @click="showAnnouncementList = false">&times;</button>
      </div>
      <div class="announcement-list">
        <div 
          v-for="announcement in filteredAnnouncements" 
          :key="announcement.noticeId"
          class="announcement-item"
          :class="{ 'unread': !isRead(announcement.noticeId) }"
          @click="viewAnnouncement(announcement)"
        >
          <div class="announcement-title">{{ announcement.title }}</div>
          <div class="announcement-date">{{ formatDate(announcement.startTime) }}</div>
        </div>
        <div v-if="filteredAnnouncements.length === 0" class="empty-message">
          暂无公告
        </div>
      </div>
    </div>
    
    <!-- 公告详情弹窗 -->
    <div v-if="selectedAnnouncement" class="modal-overlay" @click.self="closeAnnouncement">
      <div class="modal-content announcement-detail">
        <div class="modal-header">
          <h3>{{ selectedAnnouncement.title }}</h3>
          <button class="close-btn" @click="closeAnnouncement">&times;</button>
        </div>
        <div class="modal-body">
          <div class="announcement-meta">
            <span class="publish-date">发布时间：{{ formatDate(selectedAnnouncement.startTime) }}</span>
          </div>
          <div class="announcement-content">
            {{ selectedAnnouncement.content }}
          </div>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeAnnouncement">我知道了</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import api from '@/utils/axiosConfig.js'

export default {
  name: 'Notice',
  setup() {
    const userStore = useUserStore()
    const announcements = ref([])
    const showAnnouncementList = ref(false)
    const selectedAnnouncement = ref(null)
    const loading = ref(false)
    
    // 已读公告ID列表
    const readAnnouncements = reactive(new Set())
    
    // 从本地存储加载已读状态
    const loadReadStatus = () => {
      const saved = localStorage.getItem('readAnnouncements')
      if (saved) {
        try {
          const ids = JSON.parse(saved)
          ids.forEach(id => readAnnouncements.add(id))
        } catch (e) {
          console.error('加载已读公告状态失败:', e)
        }
      }
    }
    
    // 保存已读状态到本地存储
    const saveReadStatus = () => {
      const ids = Array.from(readAnnouncements)
      localStorage.setItem('readAnnouncements', JSON.stringify(ids))
    }
    
    // 获取公告数据
    const fetchAnnouncements = async () => {
      loading.value = true
      try {
        const response = await api.get('/sysNotice/getAll')
        announcements.value = response.data
        console.log('获取到的公告数据:', announcements.value)
      } catch (error) {
        console.error('获取公告失败:', error)
        // 不使用模拟数据，确保完全依赖后端API
      } finally {
        loading.value = false
      }
    }
    
    // 根据用户角色过滤公告
    const filteredAnnouncements = computed(() => {
      console.log('当前用户角色:', userStore.role)
      console.log('公告数据:', announcements.value)
      
      // 根据用户角色过滤公告
      const filtered = announcements.value.filter(announcement => {
        // 基本字段检查
        if (!announcement || !announcement.noticeId || !announcement.title || !announcement.content || announcement.targetType === undefined) {
          return false
        }
        
        // 根据用户角色过滤targetType
        // 用户端：能看到targetType为0和1的公告
        // 疾控统计端：能看到targetType为0和2的公告
        const userRole = userStore.role
        const targetType = announcement.targetType
        
        if (userRole === 'user') {
          return [0, 1].includes(targetType)
        } else if (userRole === 'statistician') {
          return [0, 2].includes(targetType)
        }
        // 其他角色默认返回所有有效公告
        return true
      })
      
      console.log('过滤后的公告:', filtered)
      
      // 排序
      return filtered.sort((a, b) => {
        // 按发布时间倒序排序
        return new Date(b.startTime || 0) - new Date(a.startTime || 0)
      })
    })
    
    // 未读公告数量
    const unreadCount = computed(() => {
      return filteredAnnouncements.value.filter(a => !readAnnouncements.has(a.noticeId)).length
    })
    
    // 检查公告是否已读
    const isRead = (id) => {
      return readAnnouncements.has(id)
    }
    
    // 切换公告列表显示状态
    const toggleAnnouncementList = () => {
      showAnnouncementList.value = !showAnnouncementList.value
    }
    
    // 查看公告详情
    const viewAnnouncement = (announcement) => {
      selectedAnnouncement.value = announcement
      // 标记为已读
      readAnnouncements.add(announcement.noticeId)
      saveReadStatus()
    }
    
    // 关闭公告详情
    const closeAnnouncement = () => {
      selectedAnnouncement.value = null
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    // 组件挂载时初始化
    onMounted(() => {
      loadReadStatus()
      fetchAnnouncements()
      
      // 监听已读状态变化并保存
      window.addEventListener('beforeunload', saveReadStatus)
    })
    
    return {
      showAnnouncementList,
      selectedAnnouncement,
      filteredAnnouncements,
      unreadCount,
      isRead,
      toggleAnnouncementList,
      viewAnnouncement,
      closeAnnouncement,
      formatDate
    }
  }
}
</script>

<style scoped>
.announcement-component {
  position: relative;
  display: inline-block;
}

.announcement-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  position: relative;
  transition: all 0.3s ease;
}

.announcement-btn:hover {
  background-color: #66b1ff;
}

.announcement-icon {
  font-size: 16px;
}

.unread-badge {
  position: absolute;
  top: -6px;
  right: -6px;
  min-width: 18px;
  height: 18px;
  padding: 0 6px;
  background-color: #f56c6c;
  color: #fff;
  border-radius: 9px;
  font-size: 12px;
  line-height: 18px;
  text-align: center;
}

.announcement-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 8px;
  width: 380px;
  max-height: 400px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  overflow: hidden;
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.announcement-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.close-btn {
  width: 24px;
  height: 24px;
  padding: 0;
  background: transparent;
  border: none;
  font-size: 18px;
  color: #909399;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background-color: #f0f2f5;
  color: #606266;
}

.announcement-list {
  max-height: 300px;
  overflow-y: auto;
}

.announcement-item {
  padding: 15px;
  border-bottom: 1px solid #f0f2f5;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.announcement-item:hover {
  background-color: #f5f7fa;
}

.announcement-item.unread::before {
  content: '';
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 8px;
  height: 8px;
  background-color: #f56c6c;
  border-radius: 50%;
}

.announcement-item.unread {
  padding-left: 25px;
}

.announcement-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.announcement-date {
  font-size: 12px;
  color: #909399;
}

.empty-message {
  padding: 40px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

/* 公告详情弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-content {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.modal-body {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}

.announcement-meta {
  margin-bottom: 15px;
  color: #909399;
  font-size: 14px;
}

.announcement-content {
  line-height: 1.8;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-word;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px;
  border-top: 1px solid #ebeef5;
}

.confirm-btn {
  padding: 8px 20px;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.confirm-btn:hover {
  background-color: #66b1ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .announcement-dropdown {
    width: 300px;
    right: auto;
    left: 0;
  }
  
  .modal-content {
    width: 95%;
    margin: 20px;
  }
}
</style>